<template>
  <el-dialog
    class="pick-dialog"
    title="更改状态"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="1100px"
  >
    <div class="form-box">
      <div class="topBtn">
        <el-button type="primary" @click="shoukuan">收款</el-button>
        <el-button type="primary" @click="jiesuan">结算</el-button>

      </div>
      <div class="names" v-if="buyerOrSeller == 'buyer'">
        <el-card class="box-card">
          <div class="search-user-box flex">
            <div class="type-txt">
              类型：收款
            </div>
            <el-input style="width:200px" @change="searchBuyer" v-model="searchNickname" placeholder="请输入用户昵称" clearable></el-input>
            <el-button type="primary" @click="searchBuyer" icon="el-icon-search">搜索</el-button>
            <el-button type="primary" @click="exportOrder1" icon="el-icon-download">导出</el-button>
          </div>
          <el-radio-group
            v-model="ruleForm.userId"
            size="small"
            @input="getOrderList"
          >
            <el-radio
              v-for="(item, index) in buyers"
              :key="index"
              :label="item.saleChanelId"
              border
              >{{ item.saleChannel + "(待收款" + item.count + ")" }}</el-radio
            >
          </el-radio-group>
        </el-card>
      </div>
      <div class="names" v-if="buyerOrSeller == 'seller'">
        <el-card class="box-card">
          <div class="search-user-box flex">
            <div class="type-txt">
              类型：结算
            </div>
            <el-input style="width:200px" @change="searchSellers" v-model="searchNickname" placeholder="请输入用户昵称" clearable></el-input>
            <el-button type="primary" @click="searchSellers" icon="el-icon-search">搜索</el-button>
            <el-button type="primary" @click="exportOrder1" icon="el-icon-download">导出</el-button>
          </div>
          <el-radio-group
            v-model="ruleForm.userId"
            size="small"
            @input="getOrderList"
          >
            <el-radio
              v-for="(item, index) in sellers"
              :key="index"
              :label="item.supplyChanelId"
              border
              >{{ item.supplyChannel + "(待结算" + item.count + ")" }}</el-radio
            >
          </el-radio-group>
        </el-card>
      </div>
      <div class="orderTable" v-loading="loading">
        <el-table
          v-if="orderList&&orderList.length"
          :data="orderList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column
            prop="no"
            label="订单编号"
            min-width="120"
          ></el-table-column>
          <el-table-column prop="goodsId" label="商品编号">
            <template slot-scope="scope">
              <span class="link" @click="openH5(scope.row.goodsId)">{{
                scope.row.goodsId
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="accountNumber" label="游戏账号">
            <!-- <template slot-scope="scope">
              <span  >{{
                scope.row.accountNumber
              }}</span>
            </template> -->
            <template slot-scope="scope">
                <span>{{scope.row.realAccountNumber||scope.row.accountNumber}}</span
                >
            </template>
          </el-table-column>
          <el-table-column prop="gameName" label="游戏名称"></el-table-column>
          <el-table-column
            prop="actualAmount"
            label="实付金额"
            v-if="buyerOrSeller == 'buyer'"
          ></el-table-column>
          <el-table-column
            prop="payTime"
            label="支付时间"
            v-if="buyerOrSeller == 'buyer'"
          ></el-table-column>
          <el-table-column
            prop=""
            label="支付状态"
          >
            <template slot-scope="scope">
              <span>{{
                commonMaps.buyerPayState[scope.row.salePay] ||
                commonMaps.buyerPayState["1"]
              }}</span
              ><br />
              <span class="link" @click="goOrderDetail(scope.row.id)"
                >订单详情</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="supplyDiscountAmount"
            label="结算金额"
            v-if="buyerOrSeller == 'seller'"
          ></el-table-column>
          <el-table-column
            prop=""
            label="结算状态"
            v-if="buyerOrSeller == 'seller'"
          >
            <template slot-scope="scope">
              <el-tag :type="commonMaps. sellerPayState[scope.row.supplySettlementState].type">{{
                  commonMaps. sellerPayState[scope.row.supplySettlementState].label || commonMaps. sellerPayState["1"].label
                }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="saleUserNickname"
            label="官方客服"
          ></el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
          ></el-table-column>
        </el-table>
        <div class="total-amount flex">
          <h3>{{buyerOrSeller=='buyer'?'合计收款：':'合计结算：'}}</h3>
          <div class="price">
            {{totalAmount}}元
          </div>
        </div>
      </div>
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="auto"
        :rules="rules"
        class="demo-ruleForm"
        
      >
        <el-form-item label="上传图片:" prop="afterImg" v-if="buyerOrSeller=='buyer'">
          <el-upload
            :action="uploadImgUrl"
            list-type="picture-card"
            :file-list="imgShowList0"
            :multiple="true"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess0"
            :on-remove="handleRemove0"
            :limit="9"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="补充描述:" prop="remark" v-if="buyerOrSeller=='buyer'">
          <el-input
            style="width: 600px"
            v-model="ruleForm.remark"
            type="textarea"
            rows="5"
            placeholder="请输入结算补充描述..."
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="center">
        <el-button @click="close('ruleForm')">关闭</el-button>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          :loading="loading"
          >{{buyerOrSeller=='buyer'?'收款':'结算'}}</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script>
import orderApi from "@/api/pickUp/order";
export default {
  name: "",
  data() {
    return {
      dialogVisible: false,
      loading: false,
      // 上传相关
      uploadImgUrl: "",
      imgShowList0: [],
      newImages0: [],
      imgFileList0: [],
      // end
      /**
       * typeReq:1买家结算 2卖家结算
orderIds:要结算的订单id数组
userId:交易方id
userName:交易方名称
img:客服上传图片
remark:备注
       */
      ruleForm: {
        typeReq: "",
        orderIds: [],
        userId: "",
        userName: "",
        img: "",
        remark: "",
      },
      rules: {},
      from: "", //来源
      buyerOrSeller: "",
      buyers: [],
      allBuyers: [],
      sellers: [],
      allSellers: [],
      searchNickname:'',//搜索用户的关键字
      orderList: [],
      selectOrders: [],
      totalAmount:0,//选中项的合计总额
      orderNos:[],
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    open(row, from) {
      this.loading = false
      this.orderList = []
      this. ruleForm={
        typeReq: "",
        orderIds:[],
        userId: "",
        userName: "",
        img: "",
        remark: "",
      },
      
      this.buyerOrSeller = "";
      this.dialogVisible = true;
    },
    // showBuyers
    shoukuan() {
      this.orderList = [];
      this.searchNickname = ''
      this.buyerOrSeller = "buyer";
      this.ruleForm.userId = ''
      this.ruleForm.typeReq = 1
      orderApi.settlementBuyer().then((res) => {
        if (res.code == 200) {
          this.buyers = res.rows;
          this.allBuyers = JSON.parse(JSON.stringify(res.rows))
        }
      });
    },
    jiesuan() {
      this.orderList = [];
      this.buyerOrSeller = "seller";
      this.searchNickname = ''
      this.ruleForm.userId = ''
      this.ruleForm.typeReq = 2
      orderApi.settlementSeller().then((res) => {
        if (res.code == 200) {
          this.sellers = res.rows;
          this.allSellers = JSON.parse(JSON.stringify(res.rows))
        }
      });
    },
    // 搜索用户 卖家
    searchSellers(){
      if(this.searchNickname.trim()){
        this.sellers = this.allSellers.filter(r=>{
          return r.supplyChannel.indexOf(this.searchNickname)>-1
        })
      }else{
        this.sellers = JSON.parse(JSON.stringify(this.allSellers))
      }
    },
    // 搜索用户 买家
    searchBuyer(){
      if(this.searchNickname.trim()){
        this.buyers = this.allBuyers.filter(r=>{
          return r.saleChannel.indexOf(this.searchNickname)>-1
        })
      }else{
        this.buyers = JSON.parse(JSON.stringify(this.allBuyers))
      }
    },
    // 导出数据 收款
    exportOrder1(){
      let obj = {
        orderStatus: 1,
        isPage: 2,
      };
      if(this.ruleForm.userId){
        if (this.buyerOrSeller == "buyer") {
          obj.saleChanelId = this.ruleForm.userId;
          obj.saleSettlementState = 1;
          obj.supplySettlementState = ''
          obj.supplyChanelId = "";
          this.loading = true;
          orderApi.exportSettlementOrderListBuyer(obj).then((res) => {
            this.$download.name(res.msg);
            this.loading = false;
          });
        
        } else if (this.buyerOrSeller == "seller") {
          obj.saleChanelId = "";
          obj.saleSettlementState = ''
          obj.supplySettlementState = 1
          obj.supplyChanelId = this.ruleForm.userId;
          this.loading = true;
          orderApi.exportSettlementOrderListSeller(obj).then((res) => {
            this.$download.name(res.msg);
            this.loading = false;
          });
        }
        
      }else{
        return this.$message.error('请先选择用户')
      }
      
        // this.$download.name(response.msg);
    },
    // 选择用户改变
    getOrderList(e) {
      let obj = {
        orderStatus: 1,
        isPage: 2,
      };
      if (this.buyerOrSeller == "buyer") {
        obj.saleChanelId = this.ruleForm.userId;
        obj.saleSettlementState = 1;
        obj.supplySettlementState = ''
        obj.supplyChanelId = "";
        if(e){
          this.buyers.forEach(b=>{
            if(b.saleChanelId==e){
              this.ruleForm.userName = b.saleChannel
            }
          })
        }else{
          this.ruleForm.userName = ''
        }
      } else if (this.buyerOrSeller == "seller") {
        obj.saleChanelId = "";
        obj.saleSettlementState = ''
        obj.supplySettlementState = 1
        obj.supplyChanelId = this.ruleForm.userId;
        if(e){
          this.sellers.forEach(b=>{
            if(b.supplyChanelId==e){
              this.ruleForm.userName = b.supplyChannel
            }
          })
        }else{
          this.ruleForm.userName = ''
        }
      }
      this.loading = true;
      orderApi.settlementOrderList(obj).then((res) => {
        this.loading = false;
        this.orderList = res.rows;
      });
    },

    // 选择订单改变
    handleSelectionChange(e) {
      // console.log("%c Line:275 🍩 e", "color:#e41a6a", e);
      this.selectOrders = e;
      this.ruleForm.orderIds = []
      this.orderNos = []
      if(e&&e.length){
        // 计算合计
        this.totalAmount = 0
        e.forEach(r=>{
          this.orderNos.push(r.no)
          this.ruleForm.orderIds.push(r.id)
          this.totalAmount +=Number(this.buyerOrSeller=='buyer'? r.actualAmount:r.supplyDiscountAmount)
        })
        this.totalAmount = Math.round(this.totalAmount*100)/100
      }else{
        this.totalAmount = 0
      }
    },
    submitForm(formName) {
      if(!this.ruleForm.orderIds||this.ruleForm.orderIds.length==0){
        return this.$message.error('请选择要结算的订单')
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //再次提醒是否确认
          let htmlTxt=
          `<div style="width:100%;word-wrap: break-word;">
            <p>结算类型：<span style="color:red;font-weight:600">${this.buyerOrSeller == "buyer"?'收款':'卖家结算'}</span></p>
            <p>商家名称：<span style="color:red;font-weight:600">${this.ruleForm.userName}</span></p>
            <p>订单数：<span style="color:red;font-weight:600">${this.ruleForm.orderIds.length}</span></p>
            <p>总结算金额：<span style="color:red;font-weight:600;font-size:20px">${this.totalAmount}元</span></p>
            ${this.buyerOrSeller == "buyer"?'<p>请确认以上款项<span style="color:red">已收到</span>，确认收款后系统将<span style="color:red">自动</span>向相关卖家结算，<span style="color:red">不可撤销</span>，请谨慎操作！</p></p>':'<p>请确认以上结算信息，提交后系统将自动结算到卖家余额，不可撤销，请谨慎操作！</p></p>'}
            </div>`
          this.$msgbox({
            title: '提示',
            message: htmlTxt,
            showCancelButton: true,
            confirmButtonText: this.buyerOrSeller == "buyer"?'确认收款':'确认结算',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString:true
          
          }).then(action => {
          this.submitFormSure()
          });
        }
      });
    },
    // 确认结算
    submitFormSure(){
          // financialStatementSaleOrder
          // 组装图片附件
          // 拼接新上传的图片
          let ziliao = []
          if (this["newImages0" ] && this["newImages0" ].length) {
                let newArr = [];
                this["newImages0" ].forEach((img) => {
                  newArr.push({
                    name: img.name,
                    url: img.response.data.filePath,
                  });
                });
                ziliao = this["imgFileList0"].concat(newArr);
              } else {
                ziliao = this["imgFileList0"];
              }
          // ziliao
          // console.log("%c Line:212 🍖 ziliao", "color:#f5ce50", ziliao);
          this.ruleForm.img = JSON.stringify(ziliao);
          this.loading = true;
          orderApi.financialStatementSaleOrder(this.ruleForm).then((res) => {
            this.dialogVisible = false;
            this.loading = false;
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.$parent.getList();
            }
          });
    },
    // 查看商品
    openH5(id){
      this.$parent.openH5(id)
    },
    // 查看订单
    goOrderDetail(id){
      this.$parent.goOrderDetail(id)
    },
    // 上传图片相关
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传9张图片");
    },
    // 图片上传成功
    handleUploadSuccess0(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages0 = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 图片删除
    handleRemove0(response) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList0.splice(key, 1); //回显的图片
        }
      });
      this.newImages0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages0.splice(key, 1); //新上传的图片
        }
      });
    },
    close(formName) {
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">

.topBtn {
  margin-bottom: 20px;
}
.orderTable {
  margin-top: 20px;
}
.total-amount{
  line-height: 50px;
}
.price{
  font-size: 24px;
  color: crimson;
}
.names {
  margin: 20px 0;
  .search-user-box{
    margin-bottom: 15px;
    align-items: center;
    .type-txt{
      font-size: 18px;
      font-weight: bold;
      margin-right: 15px;
    }
  }
}
.demo-ruleForm {
  margin-top: 20px;
  padding-right: 20px;
}

.center {
  text-align: center;
}


::v-deep .el-radio{
  margin-bottom: 10px;
  margin-left: 0 !important;
  width: 200px;
  overflow: hidden;
}

.pick-dialog >>> .el-input--medium input {
  text-align: left;
}
</style>
